﻿using FarmSmartSleep.Common.Dtos;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using FarmSmartSleep.Common.Domain.RBACFile;
using R.FarmSmartSleep.RBAC.API.Apliction.Command;
using System.Runtime.InteropServices;
using R.FarmSmartSleep.RBAC.API.Apliction.Command.Roless;
using R.FarmSmartSleep.RBAC.API.Apliction.Command.Permissions;
using R.FarmSmartSleep.RBAC.API.Common.R.Dtos;
using System;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.OpenApi.Writers;
namespace R.FarmSmartSleep.RBAC.API.Controllers
{
    /// <summary>
    /// RBAC权限管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class RBACsController : ControllerBase
    {
        private readonly IMediator mediator;
        private readonly ILogger<RBACsController> _logger;
        private readonly IConfiguration configuration;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="_mediator"></param>
        public RBACsController(IMediator _mediator, ILogger<RBACsController> logger, IConfiguration configuration)
        {
            mediator = _mediator;
            _logger = logger;
            this.configuration = configuration;
        }

        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <returns></returns>
        private string CreateTokenString()
        {
            //读取配置文件
            var jwtSettings = configuration.GetSection("JWT").Get<JwtSettings>();
            //私钥
            var secretByte = Encoding.UTF8.GetBytes(jwtSettings.SecurityKey);
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名 hs256 加密算法
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            //Claims是指用户的身份信息，例如用户名、角色、权限等，它们通常被包含在一个ClaimsPrincipal对象中。
            var claims = new[]
            {
                  new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                  new Claim("Email","pmandy@163.com"),
                  new Claim("Phone","123456"),
                  new Claim("UserId","1"),
           };

            // 生成Token
            var token = new JwtSecurityToken(
                issuer: jwtSettings.Issuer,//发行者
                audience: jwtSettings.Audience,//受众
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials,
                claims: claims
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="enm"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public async Task<IActionResult> Login([FromQuery] LoginCommon enm)
        {
            try
            {
                _logger.LogInformation("用户登陆");
                var list = await mediator.Send(enm);
                var token = CreateTokenString();

                return Ok(new
                {
                    list = list,
                    token = token
                });
            }
            catch (Exception ms)
            {
                _logger.LogError("登陆的错误" + ms.Message);
                throw;
            }
        }

        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <param name="enm"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> PhoneCaptchaCreate(PhoneCaptchaCreateCommon enm)
        {

            var list = await mediator.Send(enm);
            return list;
        }
        /// <summary>
        /// 获取验证吗
        /// </summary>
        /// <param name="enm"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Result> PhoneCaptchaListCommon([FromQuery] PhoneCaptchaListCommon enm)
        {
            var list = await mediator.Send(enm);
            return list;
        }

        /// <summary>
        /// 修改手机号
        /// </summary>
        /// <param name="enm"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Result> PhoneUpdate([FromQuery] PhoneUpdateCommon enm)
        {
            var list = await mediator.Send(enm);
            return list;
        }



        /// <summary>
        /// 验证吗雁阵
        /// </summary>
        /// <param name="enm"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> CaptchaList(CaptchaListCommon enm)
        {
            var list = await mediator.Send(enm);
            return list;
        }
        /// <summary>
        /// 添加图片
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public string UpdateImage(IFormFile file)
        {
            var fileName = file.FileName;
            var path = Directory.GetCurrentDirectory() + @"\wwwroot\Image\" + fileName;
            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                file.CopyTo(fs);
                fs.Flush();
            };
            var url = "/Image/" + fileName;
            return url;

        }

        /// <summary>
        /// 动态路由
        /// </summary>
        /// <param name="enm"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultT<List<RolterIndexDto>>> RolerIndex([FromQuery] RouterIndexCommon enm)
        {
            var list = await mediator.Send(enm);
            return list;
        }
        /// <summary>
        /// 员工添加
        /// </summary>
        /// <param name="enm"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> EmployeeRouterAdd(EmployeeRouterCommon enm)
        {
            var list = await mediator.Send(enm);
            return list;
        }
        /// <summary>
        /// 员工列表
        /// </summary>
        /// <param name="enm"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultPage<Employee>> EmployeeList([FromQuery] EmployeeListCommon enm)
        {
            var list = await mediator.Send(enm);
            return list;
        }


        /// <summary>
        /// 角色添加
        /// </summary>
        /// <param name="enm"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> RolesAdd(RolesCreateCommon enm)
        {
            var list = await mediator.Send(enm);
            return list;
        }
        /// <summary>
        /// 角色列表
        /// </summary>
        /// <param name="enm"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultPage<Roles>> RolesList([FromQuery] RolesListCommon enm)
        {
            var list = await mediator.Send(enm);
            return list;
        }
        /// <summary>
        /// 获取权限列表级联
        /// </summary>
        /// <param name="enm"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultT<List<PermissionCascaderDto>>> GetPermissionCascaderList()
        {
            var list = await mediator.Send(new PermissionCascaderCommon());
            return list;

        }
        /// <summary>
        /// 权限添加
        /// </summary>
        /// <param name="enm"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Result> PermissionAdd(PermissionCreateCommon enm)
        {
            var list = await mediator.Send(enm);
            return list;
        }
        /// <summary>
        /// 权限列表
        /// </summary>
        /// <param name="enm"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultPage<RolesPermissionListDto>> PermissionList([FromQuery] PermissionListCommon enm)
        {
            var list = await mediator.Send(enm);
            return list;
        }

        /// <summary>
        /// 获取当前登录人信息
        /// </summary>
        /// <param name="cmd">获取当前登录人信息请求对象</param>
        /// <returns>获取当前登录人信息响应对象</returns>
        [HttpPost]
        public async Task<ResultT<Employee>> DetailEmployee(EmployeeDetailCommand cmd)
        {
            var list = await mediator.Send(cmd);
            return list;
        }

        /// <summary>
        /// 修改个人用户名信息（只能修改一次）
        /// </summary>
        /// <param name="cmd">修改个人用户名信息请求对象</param>
        /// <returns>修改个人用户名信息响应对象</returns>
        [HttpPut]
        public async Task<Result> UpdateRmployee(EmployeeUpdateCommand cmd)
        {
            var list = await mediator.Send(cmd);
            return list;
        }
        /// <summary>
        /// 添加权限角色关联
        /// </summary>
        /// <param name="enm"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> PermissionRolesCreate(PermissionRolesCreateCommon enm)
        {
            var list = await mediator.Send(enm);
            return list;
        }

    }
}
